package org.abc.program.controller.admin;

import org.abc.program.util.CpachaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 生成验证码的controller
 */
@Controller
@RequestMapping(value = "/system")
public class CpachaController {

	@RequestMapping(value = "/get_cpacha", method = RequestMethod.GET)
	public void generatorCpacha(
			@RequestParam(name = "vl", required = false, defaultValue = "4") Integer vcodeLen,
			@RequestParam(name = "w", required = false, defaultValue = "100") Integer width,
			@RequestParam(name = "h", required = false, defaultValue = "30") Integer height,
			@RequestParam(name = "type", required = false, defaultValue = "loginCpacha") String cpachaType,
			HttpServletRequest request, HttpServletResponse response) {
		//1根据长度，宽度和高度创建出验证码实例
		CpachaUtil cpachaUtil = new CpachaUtil(vcodeLen, width, height);
		//2生成随机验证码
		String vCode = cpachaUtil.generatorVCode();
		//3按照验证码的用途把生成的验证码存储在当前session当中
		request.getSession().setAttribute(cpachaType, vCode);
		//4生成一个旋转字体的验证码图片
		BufferedImage bufferedImage = cpachaUtil.generatorRotateVCodeImage(vCode, true);
		try {
			//5把生成的最终验证码效果发送到客户端
			ImageIO.write(bufferedImage, "gif", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
